package rbac.service.impl;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import rbac.entity.RbacPermission;
import rbac.entity.RbacRole;
import rbac.entity.RbacUser;
import rbac.entity.RbacUserGroup;
import rbac.service.AccessControlService;
import rbac.service.UserService;


/**
 * RBAC 权限控制 service 实现类.
 * 
 * @author Huadi
 * @author Zoufengyang
 */
@Service("accessControlService")
public class AccessControlServiceImpl implements AccessControlService {

	// ---=== Fields ===--- //
	@Autowired
	@Qualifier("userService")
	private UserService userService;

	// ---=== Methods ===--- //
	@Override
	public boolean isHavePermission(RbacUser rbacUser, String resource) {
		for (String url : this.getResources(rbacUser)) {
			if (url.equals(resource)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean isHavePermission(String userName, String resource) {
		return this.isHavePermission(userService.getUser(userName), resource);
	}

	/** 得到该用户所有允许访问的 URL 串. */
	@Override
	public Set<String> getResources(RbacUser rbacUser) {
		Set<String> strSet = new HashSet<String>();
		for (RbacUserGroup ug : rbacUser.getUserGroups()) {
			for (RbacRole role : ug.getRoles()) {
				for (RbacPermission permission : role.getPermissions()) {
					for (String resource : permission.extractResources()) {
						strSet.add(resource);
					}
				}
			}
		}

		return strSet;
	}

}
